﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SYcwpb.Helpers;
using System.Collections.ObjectModel;
using SYcwpb.Models;
using SYcwpb.Commands;
using System.Windows.Input;
using SYcwpb.Access;
using System.Windows.Threading;
using System.Threading;
using SYcwpb.Views;
using System.Windows;

namespace SYcwpb.ViewModels
{
    class CSVFileViewModel:ViewModelBase
    {
        private TimeTableAccess _csvFileAccess = new TimeTableAccess();
        private CSVHelper _csvHelper;
        private CSVFileView _csvFileView;

        string _filePath;
        string _fileName;
        private bool _isInserting = false;
        private double _prosbarValue;
        private ICommand _browseFileCommand;
        private ICommand _insertCommand;
        private ICommand _deleteCommand;
        private ObservableCollection<TimeTableModel> _fileList;

        private int CSVID;

        public string FilePath
        {
            get { return _filePath; }
            set { 
                _filePath = value;

                OnPropertyChanged("FilePath");
            }
        }

        public bool IsInserting
        {
            get { return _isInserting; }
            set
            {
                _isInserting = value;
                OnPropertyChanged("IsInserting");
            }
        }

        public ObservableCollection<TimeTableModel> FileList
        {
            get
            {
                if (null == _fileList)
                {
                    _fileList = new ObservableCollection<TimeTableModel>();

                    _fileList = _csvFileAccess.GetFileList();
                }

                return _fileList;
            }
        }

        public double ProsbarValue
        {
            get { return _prosbarValue; }
            set
            {
                _prosbarValue = value;

                OnPropertyChanged("ProsbarValue");
            }
        }

        public ICommand BrowseFileCommand
        {
            get 
            {
                if (null == _browseFileCommand)
                    _browseFileCommand = new RelayCommands(Para => this.BrowseFile());

                return _browseFileCommand;
            }
        }

        public ICommand InsertCommand
        {
            get
            {
                if (null == _insertCommand)
                    _insertCommand = new RelayCommands(
                        Para => this.InsertFile(Para),
                        para => this.CanInsert()
                        );

                return _insertCommand;
            }
        }

        public ICommand DeleteCommand
        {
            get
            {
                if (null == _deleteCommand)
                    _deleteCommand = new RelayCommands(
                        Para =>this.DeleteFile(Para)
                        );
                
                return _deleteCommand;
            }
        }

        public CSVFileViewModel(CSVFileView csvFileView)
        {
            _csvFileView = csvFileView;
        }

        private void BrowseFile()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".csv"; 
            dlg.Filter = "CSV Files (.csv)|*.csv"; 
            dlg.RestoreDirectory = true;
            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results 
            if (result == true)
            {
                FilePath = dlg.FileName;
            }
        }

        private void InsertFile(object papameter)
        {
            //检查文件是否被打开
            IntPtr vHandle = CONSTDATA._lopen(_filePath, CONSTDATA.OF_READWRITE | CONSTDATA.OF_SHARE_DENY_NONE);
            if (vHandle == CONSTDATA.HFILE_ERROR)
            {
                MessageBoxHelper.ShowError("文件被占用！请关闭文件后重试！");
                return;
            }

            int command = (int)papameter;
            if (command < 0)
            {
                MessageBoxHelper.ShowError("请选择时刻表类型！");
                return;
            }
            CSVID = command;

            CONSTDATA.CloseHandle(vHandle);

            Action InsertFileDelegate = this.Insert;
            _isInserting = true;
            InsertFileDelegate.BeginInvoke(new AsyncCallback(InsertCallBack), InsertFileDelegate);
        }

        private bool CanInsert()
        {
            return !string.IsNullOrEmpty(_filePath) && !IsInserting;
        }

        private void Insert()
        {
            string filePath = FilePath.Substring(0, FilePath.LastIndexOf('\\'));
            _fileName = FilePath.Substring(FilePath.LastIndexOf('\\') + 1);

            _csvHelper = new CSVHelper(filePath, _fileName);
            _csvHelper.InsertProcessEvent += new EventHandler<InsertProcessEventArgs>(csvHelper_InsertProcessEvent);
            _csvHelper.InsertFinishedEvent += new EventHandler(_csvHelper_InsertFinishedEvent);
            _csvHelper.TransferCSVToDB(SqlDataLayer.ConnStr, CSVID);
        }

        void csvHelper_InsertProcessEvent(object sender, InsertProcessEventArgs e)
        {
            ProsbarValue = e.State;
        }

        void _csvHelper_InsertFinishedEvent(object sender, EventArgs e)
        {
            
            _csvFileView.Dispatcher.Invoke(DispatcherPriority.Normal,new DelegateFileListAddItem(FileListAddItem));
        }

        private void InsertCallBack(IAsyncResult iar)
        {
            Action calback = (Action)iar.AsyncState;
            calback.EndInvoke(iar);

            _isInserting = false;
            ProsbarValue = 0;
        }

        private delegate void DelegateFileListAddItem();
        private void FileListAddItem()
        {
            string name = _fileName.Substring(0, _fileName.IndexOf('.'));
            FileList.Add(TimeTableModel.CreateCSVFileModel(_csvFileAccess.GetIdByName(name), name));

            MessageBoxHelper.ShowTips("导入文件完成！");
        }

        private void DeleteFile(object parameter)
        {
            TimeTableModel deleteModel = (TimeTableModel)parameter;

            if (null != deleteModel)
            {
                if ( MessageBoxHelper.ConfirmYesNo(string.Format("确定要执行删除时刻表 {0} 操作？", deleteModel.Name))
                    )
                {
                    if (_csvFileAccess.DeleteFile(deleteModel))
                    {
                        FileList.Remove(deleteModel);
                        MessageBoxHelper.ShowTips(string.Format("时刻表 {0} 已从数据库中清除!",deleteModel.Name));
                    }
                    else { MessageBoxHelper.ShowError("无法执行删除操作！"); }
                }
            }
            else
            {
                MessageBoxHelper.ShowError("请先选择需要删除的文件");
            }
        }

    }
}
